<?php

//@require_once('./lib/base.inc');

$members_batch_toSend = array();
$batches              = array();

function _getBatchText($tpl_file,$pars=array()){
  	global $param;
	$l_smarty = new Smarty;
	$l_smarty->compile_check = true;
	$l_smarty->cache_dir = './lib/cache/';
	$l_smarty->caching = false;
	$l_smarty->debugging = SMARTY_DEBBUG;
	$l_smarty->template_dir=PATH_TPL;
	$l_smarty->compile_dir='./ztemp';
	$l_smarty->left_delimiter='{';
	$l_smarty->right_delimiter='}';

    $l_smarty->assign($pars);
    $l_smarty->assign('today',time());
   	$rep = trim($l_smarty->fetch($tpl_file));

    return $rep;
}


function _sendMail($mail,$objet,$message,$important=false,$addLayout='layout'){
	$headers="";
	//$headers.="To: $mail\n";
	$headers.="From: webmaster@association-lolita.com\n";
	$headers.="Reply-To: webmaster@association-lolita.com\n";
	$headers.="Bcc: webmaster@association-lolita.com\n";
	$headers.="Content-Type: text/html; charset=utf-8";

    if($important){
        $headers .= "X-Priority: 1 (Higuest)\n";
        $headers .= "X-MSMail-Priority: High\n";
        $headers .= "Importance: High\n";
    }

    if($addLayout!=''){
      $pars = array('content'=>$message,'layout'=>$addLayout);
      $message = _getBatchText('batch_layout.tpl', $pars);
    }

//    $objet    = utf8_encode($objet);
//    $message  = utf8_encode($message);

    spy("mail=$mail - objet=$objet - message=$message");
    if($_SERVER['SERVER_ADDR']!='127.0.0.1'){
      mail($mail,$objet,$message,$headers);
    }
}

/**
 *
 * @return
 * @param string $mail Adresse mail
 * @param string $objet Objet du mail
 * @param array $params[optional] Pramètres de la template
 * @param string $objet[optional] Message du mail si pas tpl
 */
function envoyerBatchJouteurs(&$membre_batch,$objet='',$objetTyp){
    if(!isset($membre_batch['membre_email'])) return;

    $mail = $membre_batch['membre_email'];

    $objet = '';
    $du = $membre_batch['_batch']['_du'];
    $au = $membre_batch['_batch']['_au'];

    $pars=array(
         'tpl'=>'planning'
        ,'planning'=>join('<br />',$membre_batch['_batch']['_txt'])
        ,'membre'=>  $membre_batch
        ,'du'=>  $du
        ,'au'=>  $au
        ,'today'=> time()
    );

    $message = _getBatchText('batch_text.tpl',$pars);

    $pars=array(
        'du'=>  $du
        ,'au'=>  $au
        ,'tpl'=>  'objet'
        ,'objetTyp'=>$objetTyp
        ,'today'=> time()
    );

	$objet = _getBatchText('batch_text.tpl',$pars);

    _sendMail($mail, $objet, $message);

    unset($membre_batch);

}

/**
 *
 * @return
 * @param string $mail Adresse mail
 * @param string $objet Objet du mail
 * @param array $params[optional] Pramètres de la template
 * @param string $objet[optional] Message du mail si pas tpl
 */
function envoyerWarnMail($mail,$match,$membre,$type=''){

    if(!is_array($membre))
       $membre = array($membre);

    foreach(array('membre_nom','membre_prenom','membre_surnom') as $val){
      if(!isset($membre[$val]))
        $membre[$val] = '';
    }

    $pars = array(
       'tpl'=>$type
       ,'match'=>$match
       ,'membre'=>$membre
       ,'today'=> time()
    );


	$message = _getBatchText('batch_warn_text.tpl',$pars);

    $pars = array_merge($pars,array(
       'tpl'=>'objet'
       ,'objetTyp'=>$type
       ,'today'=> time()
    ));

	$objet = _getBatchText('batch_warn_text.tpl',$pars);

    _sendMail($mail, $objet, $message, true);

}

function getBatchText(&$membre,$params=array(),$from='batch_text.tpl'){
  global $members_batch_toSend;

 	if(!isset($params['tpl'])) $params['tpl']=array();

    $message = _getBatchText($from,$params);

    if(isset($params['directSend']) && $params['directSend']==true){
      return $message;
    }

    if($message!=''){

      $id = $membre['membre_id'];

      if(isset($membre['membre_get_batch_mail']) && $membre['membre_get_batch_mail']==0){
        return;
      }

      if(!isset($members_batch_toSend[$id])){
        $members_batch_toSend[$id] = $membre;
      }

      if(!isset($members_batch_toSend[$id]['_batch'])){
        $members_batch_toSend[$id]['_batch']=array();
      }
      if(!isset($members_batch_toSend[$id]['_batch']['_txt'])){
        $members_batch_toSend[$id]['_batch']['_txt']=array();
      }

      if(!isset($members_batch_toSend[$id]['_batch']['_du'])){
        $members_batch_toSend[$id]['_batch']['_du']=0;
      }

      if(!isset($members_batch_toSend[$id]['_batch']['_au'])){
        $members_batch_toSend[$id]['_batch']['_au']=0;
      }

      $members_batch_toSend[$id]['_batch']['_txt'][] = $message;

      if(isset($params['match']) && isset($params['match']['match_date'])){
        if($members_batch_toSend[$id]['_batch']['_du']==0){
          $members_batch_toSend[$id]['_batch']['_du'] = $params['match']['match_date'];
        } else {
          $members_batch_toSend[$id]['_batch']['_du'] = min($members_batch_toSend[$id]['_batch']['_du'],$params['match']['match_date']);
        }

        $members_batch_toSend[$id]['_batch']['_au'] = max($members_batch_toSend[$id]['_batch']['_au'],$params['match']['match_date']);
      }
    }
}

function getMembresEquipes(&$membres,&$equipes){
  global $db,$param,$saison_courante_id;

  $sql=sprintf('select
      t_m.membre_nom
      ,t_m.membre_prenom
      ,t_m.membre_email
      ,t_m.membre_id
      ,t_m.membre_get_batch_mail
      ,t_mes.equipe_id

      from t_membres as t_m
      inner join t_liens_mes as t_mes using(membre_id)
      inner join t_equipes as t_e on t_e.equipe_id = t_mes.equipe_id
      where t_mes.saison_id=%d and t_m.membre_email<>""
      order by t_mes.equipe_id,t_m.membre_id',$saison_courante_id);

  $membres = $db->SelectAllBy($sql,'equipe_id,membre_id');

  $sql=sprintf('select t_e.equipe_nom,t_e.equipe_id
      from t_equipes as t_e
      inner join t_liens_es as t_es using(equipe_id)
      where t_es.saison_id=%d
      order by t_es.equipe_id',$saison_courante_id);

  $equipes = $db->SelectAllBy($sql,'equipe_id');

}

function getMembresActifs(&$membres){
  global $db,$param,$saison_courante_id;
  $select = "select
      t_m.membre_nom
      ,t_m.membre_prenom
      ,t_m.membre_email
      ,t_m.membre_id
      ,t_m.membre_get_batch_mail
      from t_membres as t_m";

  $sql=sprintf('('.$select.'
      inner join t_liens_mes as t_mes using(membre_id)
      where t_mes.saison_id=%1$d and t_m.membre_email<>"")
          UNION ('.$select.'
      inner join t_liens_mfs as t_mfs using(membre_id)
      where t_mfs.saison_id=%1$d and t_m.membre_email<>"")
      order by membre_id',$saison_courante_id);
      spy($sql);
  $membres = $db->SelectAllBy($sql,'membre_id');
}

/**
 *
 * @global DataBase $db
 * @global array $param
 * @global int $saison_courante_id
 * @param date $du
 * @param date $au
 * @return array
 */
function getMatchs($du,$au,$batch_name=''){
  global $db,$param,$saison_courante_id; /* @var $db DataBase */

  $ret = array();

  // Pas la joute libre
  $sql = sprintf("select match_id,match_equipe_a,match_equipe_b,match_logistique,match_affichage,match_date,match_compet_id
  from t_matchs as t_m where match_saison_id=%d and match_compet_id %s and match_date between %d and %d",$saison_courante_id,'in (1,2,3)',$du,$au);

  if(!empty($batch_name)){
    $sql = sprintf("%s and match_id not in (select match_id from t_batch_match where batch_name='%s')",$sql,$batch_name);
  }
  spy($sql);
  $ret = $db->SelectAll($sql);

  if(!is_array($ret)){
    $ret = array();
  }

  return($ret);
}

function avertirResponsables($qui,$match){
  global $db,$saison_courante_id;

  $sql  ="select * from t_fonctions_warn where fonction_warn_name='$qui'";
  $row = $db->SelectFirst($sql);

  if($row){
    if(empty ($row['fonction_id_lst']))       $row['fonction_id_lst']     ='0';
    if(empty ($row['fonction_type_id_lst']))  $row['fonction_type_id_lst']='0';

    $mails = array();
    $sql="select fonction_mail,fonction_lib as membre_prenom from t_fonctions where fonction_id in ({$row['fonction_id_lst']}) and fonction_mail<>''";
    $mails = array_merge($mails,$db->SelectAllBy($sql,'fonction_mail'));
    $sql="select fonction_mail,fonction_type_lib as membre_prenom from t_fonctions_type where fonction_type_id in ({$row['fonction_type_id_lst']}) and fonction_mail<>''";
    $mails = array_merge($mails,$db->SelectAllBy($sql,'fonction_mail'));

    $sql = "select * from t_membres as t_m
            inner join t_liens_mfs as t_l_mfs using(membre_id)
            where ( t_l_mfs.fonction_id in ({$row['fonction_id_lst']})
            or      t_l_mfs.fonction_type_id in ({$row['fonction_type_id_lst']}))
            and t_l_mfs.saison_id = $saison_courante_id
            ";

    $membres = $db->SelectAllBy($sql,'membre_email');

    $mails = array_merge($mails,$membres);

    foreach($mails as $mail=>$membre){
      envoyerWarnMail($mail,$match,$membre,$qui);
    }
  }

}

function avertirQui($qui = array(),$membres,$match,$params=array()){
    global $db;
    $check = array('match_equipe_a','match_equipe_b','match_logistique','match_affichage');

    foreach($check as $key){
      if(isset($match[$key]) && isset($membres[$match[$key]]) && !is_array($membres[$match[$key]])){
        $membres[$match[$key]] = array();
      }
    }

    if(!is_array($qui)){
      $qui = array($qui);
    }

    foreach($qui as $key=>$val){
      $key = 'match_' .$val;
//      if(isset($match[$key]) && isset($membres[$match[$key]]) && !is_array($membres[$match[$key]])){
//        $membres[$match[$key]] = array();
//      }

      if($match[$key]==0){
          // Match sans équipes
          switch($val){
            case 'equipe_a':
              if ($match['match_equipe_b']==0)
                 break; // On avertira quans b arrivera
            case 'equipe_b':
              avertirResponsables("match-sans-equipe",$match);
              break;
            case 'logistique':
              avertirResponsables("match-sans-logistique",$match);
              break;
            case 'affichage':
              // On va voir si il existe un match dans la semaine
              // avec de l'affichage, et ca devrait être les mêmes
              $from = $match['match_date'] - (7 * 24 * 60 * 60);
              $to   = $match['match_date'] + (2 * 24 * 60 * 60);

              $sql = sprintf('select count(*) from t_matchs where match_date between %d and %d and match_compet_id %s and match_id<>%d and match_affichage<>0',$from,$to,'<>4',$match['match_id']);
              if($db->Count($sql)==0){
                avertirResponsables("match-sans-affichage",$match);
              }
              break;
            default:
              avertirResponsables("match-sans-$val",$match);
          }

      }
      else{
        if(isset($match[$key]) && isset($membres[$match[$key]])){
          foreach($membres[$match[$key]] as $id=>$membre){
              getBatchText($membre,array_merge($params,array('tpl'=>$val,'membre'=>$membre,'match'=>$match,'equipe_a'=>$match['match_equipe_a'],'equipe_b'=>$match['match_equipe_b'])));
          }
        }
      }
    }
}

function avertirMembres($membres,$tpl='',$params=array(),$onlyBatchMail=true){
    global $db;

    foreach($membres as $membre){
      if($onlyBatchMail==true && (!isset($membre['membre_get_batch_mail']) || $membre['membre_get_batch_mail']==0)) continue;
    /* @var $message */
      $message='';
      $message = getBatchText($membre,array_merge($params,array('tpl'=>$tpl,'membre'=>$membre)));
      //spy("<h1>Ici$message</h1>");
      if(isset($params['directSend']) && $params['directSend']==true){
        _sendMail($membre['membre_email'], '', $message);
      }
    }

}

function isTesting($batch_name){
  global $db;
  $ret = false;
  $sql = "Select count(*) from t_batch where batch_name='$batch_name' and batch_testing=1";
  if($db->Count($sql)){
    $ret = true;
  }

  return $ret;
}

function registerMatchAsBatched($match,$batch_name){
    global $db,$param,$saison_courante_id,$batches;

    if(!isTesting($batch_name)){
      $sql = sprintf('Insert into t_batch_match (batch_name,match_id,batch_match_date) values("%s",%d,FROM_UNIXTIME(UNIX_TIMESTAMP()))',$batch_name,$match['match_id']);
      $db->Insert($sql);
    }
}

function process_planningMois($prop){
	global $db,$param,$saison_courante_id;
    $db; /* @var $db DataBase */
    $membres = array();
    $equipes = array();

    getMembresEquipes($membres,$equipes);
    getMembresActifs($membres);

    $from	=	strtotime($prop['batch_from'],strtotime('tomorrow'));
    $to		=	strtotime($prop['batch_to'],$from);
    $matchs =   getMatchs($from,$to,$prop['batch_name']);
    $params = array('tpl'=>'match','mois'=>$from,'directSend'=>true,'matchs'=>$matchs,'equipes'=>$equipes);
    avertirMembres($membres,'planningMois',$params);
}

function process_match2Sem($prop){
	global $db,$param,$saison_courante_id;

    $db; /* @var $db DataBase */

    $membres = array();
    $equipes = array();

    getMembresEquipes($membres,$equipes);

    $from	=	strtotime($prop['batch_from'],strtotime('tomorrow'));
    $to		=	strtotime($prop['batch_to'],$from);

    foreach(getMatchs($from,$to,$prop['batch_name']) as $key=>$match){
      $params = array('tpl'=>'match','match'=>$match,'equipes'=>$equipes,'mois'=>true);

      avertirQui('logistique',$membres,$match,$params);
      avertirQui('affichage',$membres,$match,$params);
      avertirQui(array('equipe_a','equipe_b'),$membres,$match,$params);

      registerMatchAsBatched($match,$prop['batch_name']);
    }

}

function process_matchToday($prop){
	global $db,$param,$saison_courante_id;

    $db; /* @var $db DataBase */

    $membres = array();
    $equipes = array();

    getMembresEquipes($membres,$equipes);

    if (strtolower($prop['batch_from'])=='today'){
      $from	=	strtotime($prop['batch_from']);
    } else {
      $from	=	strtotime($prop['batch_from'],strtotime('tomorrow'));
    }
    $to		=	strtotime($prop['batch_to'],$from)-1;

    foreach(getMatchs($from,$to,$prop['batch_name']) as $key=>$match){
      $params = array('tpl'=>'match','match'=>$match,'equipes'=>$equipes);

      avertirQui('logistique',$membres,$match,$params);
//      avertirQui('affichage',$membres,$match,$params);
      avertirQui(array('equipe_a','equipe_b'),$membres,$match,$params);

      registerMatchAsBatched($match,$prop['batch_name']);
    }

}

function doBatch($prop){
  spy($prop['batch_name']);
  switch($prop['batch_name']){
    case ' ':
      break;
    default:
      $functionName = $prop['batch_action']=='' ? 'process_'.ucfirst($prop['batch_name']) : $prop['batch_action'];
      if(function_exists($functionName)){
        $functionName($prop);
      }
  }

}

function creerProchainTick($batch,$strtime=''){
  global $db,$param,$saison_courante_id;


  if(!is_array($batch) && $strtime == ''){
    $sql = sprintf("select * from t_batch where batch_name = '%s' limit 1",$batch);
    $batch = $db->SelectFirst($sql);
  }

  $au =  strtotime($strtime=='' ? $batch['batch_from'] : $strtime);
//  $au = date('Y-m-d',$au);

  $sql = sprintf("Insert into t_batch_tick (batch_name,batch_tick_date) values('%s',FROM_UNIXTIME(%d))",$batch['batch_name'],$au);

  $db->Insert($sql);

}
/**
 * Process batch : Exectue des taches planifiées si besoin est
 */
function processBatch(){
return ;
//    return;
//  avertirLogistique(6);
//  avertirJouteurs(1);
//  return;

//  spy('today ' . strtotime('Today'));
//  spy('tomorrow ' . strtotime('Tomorrow'));
//  spy('1/01/11 ' . strtotime('1 Jan 2011'));
//  spy('first day of month midnight' . strtotime('first day of this month midnight'));
//  spy('first day' . strtotime('first day'));
//  spy('31/01/11 ' . strtotime('31 Jan 2011'));
//  spy('last day of month midnight' . strtotime('last day of this month midnight'));
//  spy('last day' . strtotime('last day'));
//
//  return;

  global $db,$param,$saison_courante_id,$members_batch_toSend;

  $db; /* @var $db DataBase */

  $sql = 'select * from t_batch where batch_active = 1';

  foreach($db->SelectAll($sql) as $row){
    // On recherche s'il y'a des lignes atives dans les batch a faire
    $sql = sprintf('select count(*) from t_batch_tick as t_b_t where batch_name = "%s" and batch_tick_process_date = 0',$row['batch_name']);

    if($db->Count($sql)==0){// && !isTesting($row['batch_name'])){
     creerProchainTick($row);
    }
  }


  $sql = 'select * from t_batch_tick as t_b_t inner join t_batch as t_b using(batch_name) where t_b.batch_active=1 and t_b_t.batch_tick_date<=NOW() and t_b_t.batch_tick_process_date = 0';

  foreach($db->SelectAll($sql) as $row){
    doBatch($row);
    if(!isTesting($row['batch_name'])){
      $sql = 'Update t_batch_tick set batch_tick_process_date =  NOW() where batch_tick_id = '.$row['batch_tick_id'];
      $db->Update($sql);
      creerProchainTick($row,$row['batch_to']);
    }
  }

  foreach($members_batch_toSend as $key=>$membre_batch){
    envoyerBatchJouteurs($membre_batch,'','planning');
  }
}

